package com.xinhe.web.service;

import com.xinhe.web.common.BusinessException;
import com.xinhe.web.common.Result;
import com.xinhe.web.entity.Role;
import com.xinhe.web.entity.User;
import com.xinhe.web.reposity.AuthRoleRepository;
import com.xinhe.web.reposity.AuthUserRepository;
import com.xinhe.web.session.UserSessionManager;
import com.xinhe.web.session.UserSessionView;
import com.xinhe.web.util.Snowflake;
import com.xinhe.web.vo.UserRegisterModel;
import com.xinhe.web.vo.UserRoleModel;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class UserService {
    @Autowired
    AuthUserRepository authUserRepository;
    @Autowired
    UserRoleService userRoleService;
    @Autowired
    AuthRoleRepository authRoleRepository;
    @Autowired
    UserSessionManager userSessionManager;

    @Transactional(rollbackFor = {Exception.class})
    public Result<Long> registerUser(UserRegisterModel model) {
        User user = new User();
        user.setId(Snowflake.generateId());
        if (!Objects.isNull(model.getPhoneNumber())){
            user.setPhoneNumber(model.getPhoneNumber());
        }
        if (!Objects.isNull(model.getParentId())){
            user.setParentId(model.getParentId());
        }
        if (!Objects.isNull(model.getPlatformUserId())){
            user.setPlatformUserId(model.getPlatformUserId());
        }
        this.authUserRepository.save(user);
        if (null != model.getRoleIds() && 0 < (model.getRoleIds()).length) {
            Result roleResult = this.userRoleService.saveUserRole(new UserRoleModel(user.getId(), model.getRoleIds()));
            if (roleResult.getCode() !=0) {
                throw new BusinessException(9001,"saveUserRole保存角色失败");
            }
        }
        return Result.ok(user.getId());
    }

    @Transactional(rollbackFor = {Exception.class})
    public Result userLogin(Long userId,Set<Long> roleIds,Map<String, String> initExtendValue) {
        List<Role> roles = this.authRoleRepository.findByUserId(userId);
        if (CollectionUtils.isEmpty(roles)) {
            return Result.failed(2001,"无权限");
        }
        List<UserSessionView.RoleView> roleViews = new ArrayList<>();
        Boolean roleValid = true;
        UserSessionView.RoleView roleView = null;
        for (Long roleId : roleIds) {
            for (Role r : roles) {
                if (roleId.equals(r.getId())) {
                    roleView = new UserSessionView.RoleView();
                    BeanUtils.copyProperties(r, roleView);
                    roleViews.add(roleView);
                }
            }
            roleValid = false;
        }
        if (!roleValid) {
            return Result.failed(2002,"无权限");
        }
        UserSessionView sessionView = new UserSessionView(userId,roleViews);
        if (!Objects.isNull(initExtendValue)){
            sessionView.setExtendValue(initExtendValue);
        }
        //保存登陆用户信息到redis
        this.userSessionManager.saveUserSession(sessionView);
        return Result.ok(sessionView);
    }

    public Result findRole(Long userId) {
        UserSessionView session = this.userSessionManager.getUserSession();
        return Result.ok(session.getRoles());
    }

}
